package com.healthcarex.hip.saas.security.util;

import com.healthcarex.hip.saas.security.vo.AuthUserDetail;
import com.healthcarex.hip.saas.security.vo.SimpleUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author  ChenPan
 * @date   2018/6/25 13:54
 * description:
 */
public final class SecurityUtils {

    /**
     * 获取当前用户的用户名
     *
     * @return
     */
    public static String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = null;
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            currentUserName = authentication.getName();

        }
        return currentUserName;
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static SimpleUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (SimpleUser) authentication.getPrincipal();
    }

    /**
     * 当前用户是否拥有权限
     *
     * @param role
     * @return
     */
    public static boolean hasRole(String role) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return false;
        }

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (role.equals(auth.getAuthority())) {

                return true;
            }
        }

        return false;
    }
}
